<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:h1th="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Chatroom</title>

    <script th:inline="javascript">

        var socket;
        if(window.WebSocket){

            socket = new WebSocket("ws://localhost:9000/ws");
            socket.onmessage = function(event){
                var ta = document.getElementById("responseText");
                ta.value = ta.value + "\n" + event.data;
            };

            socket.onopen = function(event){
                var ta = document.getElementById("responseText");
                ta.value = "成功进入聊天室！";
            };

            //服务器关闭会执行该方法
            socket.onclose = function (ev) {
                var ta = document.getElementById("responseText");
                ta.value = ta.value + "\n" + "退出聊天室！!";
            }

        }else{
            alert("浏览器不支持WebSocket");
        }


        function send(message) {
            if(!window.WebSocket){
                return;
            }
            if(socket.readyState === WebSocket.OPEN){
                var mes = [[${username}]]+":"+message;
                socket.send(mes);
                //发送完消息后对消息框进行清楚
                document.getElementById("message").value = '';
            }else{
                alert("连接尚未开启！");
            }
        }

    </script>
</head>
<body>
    <h1>用户：<span id="username" th:text="${username}"></span></h1>
    <div>
        <textarea id = "responseText" style="width:400px;height: 200px"></textarea><br/>
        <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空内容">
    </div>

    <div>
        <form onsubmit="return false;">
            <textarea id="message" name="message" style="width:400px; height: 200px"></textarea><br/>
            <input type="button" value="发送数据" onclick="send(this.form.message.value)"/><br/>
        </form>
    </div>

</body>
</html>